import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import json
import threading
import files_gener_comment as generator
import os
import logging
import sys
import verify_directory_comments as verifier

class CommentGeneratorGUI:
    def __init__(self, root):
        # Set up logging
        if getattr(sys, 'frozen', False):
            # 如果是打包后的可执行文件
            base_path = os.path.dirname(sys.executable)
        else:
            # 如果是开发环境
            base_path = os.path.dirname(__file__)
        
        log_dir = os.path.join(base_path, 'log')
        os.makedirs(log_dir, exist_ok=True)
        log_file = os.path.join(log_dir, 'comment_generator.log')
        
        # Create log file if it doesn't exist
        if not os.path.exists(log_file):
            open(log_file, 'a').close()
        
        logging.basicConfig(
            filename=log_file,
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )
        
        self.root = root
        self.root.title("代码注释生成器")
        self.root.geometry("800x600")
        
        # 创建主框架
        self.main_frame = ttk.Frame(root, padding="10")
        self.main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 文件夹选择
        ttk.Label(self.main_frame, text="目标文件夹:").grid(row=0, column=0, sticky=tk.W)
        self.folder_paths = []
        self.folder_listbox = tk.Listbox(self.main_frame, height=5, width=70)
        self.folder_listbox.grid(row=1, column=0, columnspan=2, sticky=(tk.W, tk.E))
         
        ttk.Button(self.main_frame, text="添加文件夹", command=self.add_folder).grid(row=2, column=0, sticky=tk.W)
        ttk.Button(self.main_frame, text="移除选中", command=self.remove_folder).grid(row=2, column=1, sticky=tk.W)
        
        # 文件类型
        ttk.Label(self.main_frame, text="文件类型 (用逗号分隔):").grid(row=3, column=0, sticky=tk.W)
        self.file_types = ttk.Entry(self.main_frame, width=50)
        self.file_types.insert(0, ".java,.ts,.vue")
        self.file_types.grid(row=4, column=0, columnspan=2, sticky=(tk.W, tk.E))
        
        # 提示文本
        ttk.Label(self.main_frame, text="注释提示文本:").grid(row=5, column=0, sticky=tk.W)
        self.prompt = tk.Text(self.main_frame, height=3, width=50)
        self.prompt.insert("1.0", "请给这段代码的每一行加中文注释，去掉不必要的空行，只输出完整的代码块给我")
        self.prompt.grid(row=6, column=0, columnspan=2, sticky=(tk.W, tk.E))
        
        # 坐标配置
        ttk.Label(self.main_frame, text="坐标配置:").grid(row=7, column=0, sticky=tk.W)
        self.coordinates_frame = ttk.LabelFrame(self.main_frame, text="坐标设置", padding="5")
        self.coordinates_frame.grid(row=8, column=0, columnspan=2, sticky=(tk.W, tk.E))
        
        self.coordinate_entries = {}
        self.create_coordinate_inputs()
        
        # 控制按钮
        self.start_button = ttk.Button(self.main_frame, text="开始运行", command=self.start_generation)
        self.start_button.grid(row=9, column=0, pady=10)
        
        self.stop_button = ttk.Button(self.main_frame, text="停止运行", command=self.stop_generation, state=tk.DISABLED)
        self.stop_button.grid(row=9, column=1, pady=10)
        
        self.verify_button = ttk.Button(self.main_frame, text="验证文件", command=self.verify_files)
        self.verify_button.grid(row=9, column=2, pady=10)
        
        # 运行状态
        self.running = False
        self.thread = None

    def create_coordinate_inputs(self):
        default_coords = {
            'GPT输入框位置': (977, 982),
            '重新生成按钮位置': (1088, 900),
            '关闭提示按钮位置': (1495, 862),
            '滚动区域位置': (1725, 780),
            '备用复制按钮位置': (1522, 837)
        }
        
        for i, (name, (x, y)) in enumerate(default_coords.items()):
            ttk.Label(self.coordinates_frame, text=f"{name}:").grid(row=i, column=0, sticky=tk.W)
            x_entry = ttk.Entry(self.coordinates_frame, width=10)
            y_entry = ttk.Entry(self.coordinates_frame, width=10)
            x_entry.insert(0, str(x))
            y_entry.insert(0, str(y))
            x_entry.grid(row=i, column=1, padx=5)
            y_entry.grid(row=i, column=2, padx=5)
            coord_key = {
                'GPT输入框位置': 'input_box',
                '重新生成按钮位置': 'regenerate_btn',
                '关闭提示按钮位置': 'close_prompt',
                '滚动区域位置': 'scroll_area',
                '备用复制按钮位置': 'alternate_copy'
            }[name]
            self.coordinate_entries[coord_key] = (x_entry, y_entry)

    def add_folder(self):
        folder = filedialog.askdirectory()
        if folder:
            folder = folder.replace('/', '\\')
            self.folder_paths.append(folder)
            self.folder_listbox.insert(tk.END, folder)

    def remove_folder(self):
        selection = self.folder_listbox.curselection()
        if selection:
            self.folder_paths.pop(selection[0])
            self.folder_listbox.delete(selection)

    def get_coordinates(self):
        coords = {}
        for name, (x_entry, y_entry) in self.coordinate_entries.items():
            try:
                x = int(x_entry.get())
                y = int(y_entry.get())
                coords[name] = (x, y)
            except ValueError:
                messagebox.showerror("错误", f"{name} 坐标必须是数字")
                return None
        return coords

    def start_generation(self):
        if not self.folder_paths:
            messagebox.showerror("错误", "请至少选择一个文件夹")
            return
            
        file_types = [t.strip() for t in self.file_types.get().split(",")]
        coordinates = self.get_coordinates()
        if coordinates is None:
            return
            
        prompt = self.prompt.get("1.0", tk.END).strip()
        
        self.running = True
        self.start_button.config(state=tk.DISABLED)
        self.stop_button.config(state=tk.NORMAL)
        
        # 在新线程中运行生成器
        self.thread = threading.Thread(
            target=self.run_generator,
            args=(self.folder_paths, file_types, coordinates, prompt)
        )
        self.thread.start()

    def run_generator(self, folder_paths, file_types, coordinates, prompt):
        try:
            logging.info("Starting comment generation")
            logging.info(f"Folders: {folder_paths}")
            logging.info(f"File types: {file_types}")
            
            success = generator.generate_comments(folder_paths, file_types, coordinates, prompt, lambda: self.running)
            
            if not success:
                logging.warning("Comment generation incomplete")
                self.root.after(0, lambda: messagebox.showwarning("警告", "代码注释生成未完全完成"))
            else:
                logging.info("Comment generation completed successfully")
                self.root.after(0, lambda: messagebox.showinfo("成功", "代码注释生成已完成"))
        except Exception as e:
            logging.error(f"Error during generation: {str(e)}", exc_info=True)
            self.root.after(0, lambda: messagebox.showerror("错误", f"运行时发生错误: {str(e)}"))
        finally:
            self.running = False
            self.root.after(0, self.update_buttons)

    def update_buttons(self):
        self.start_button.config(state=tk.NORMAL)
        self.stop_button.config(state=tk.DISABLED)

    def stop_generation(self):
        if self.running:
            self.running = False
            messagebox.showinfo("提示", "正在停止运行...")
            # 等待线程结束
            if self.thread and self.thread.is_alive():
                self.thread.join(timeout=1.0)  # 等待最多1秒

    def verify_files(self):
        """验证选中文件夹中的文件"""
        if not self.folder_paths:
            messagebox.showerror("错误", "请至少选择一个文件夹")
            return
            
        file_types = [t.strip() for t in self.file_types.get().split(",")]
        
        # 创建新线程运行验证
        verify_thread = threading.Thread(
            target=self.run_verification,
            args=(self.folder_paths, file_types)
        )
        verify_thread.start()

    def run_verification(self, folder_paths, file_types):
        """在新线程中运行验证过程"""
        try:
            logging.info("Starting file verification")
            logging.info(f"Folders to verify: {folder_paths}")
            logging.info(f"File types: {file_types}")
            
            for folder in folder_paths:
                verifier.verify_directory_comments(folder, file_types)
            
            self.root.after(0, lambda: messagebox.showinfo("成功", "文件验证完成"))
            
        except Exception as e:
            logging.error(f"Error during verification: {str(e)}", exc_info=True)
            self.root.after(0, lambda: messagebox.showerror("错误", f"验证过程中发生错误: {str(e)}"))

    def __del__(self):
        self.stop_generation()
        if self.thread and self.thread.is_alive():
            self.running = False
            self.thread.join(timeout=2.0)  # 给予更多时间让线程完成

if __name__ == "__main__":
    root = tk.Tk()
    app = CommentGeneratorGUI(root)
    
    def on_closing():
        app.stop_generation()
        root.destroy()
    
    root.protocol("WM_DELETE_WINDOW", on_closing)
    root.mainloop() 